const  connection  = require("../app/database")

class RoleService {
  async createRole(roleName, roleDesc) {
    const statement = `
      INSERT INTO role (roleName,roleDesc) VALUES (?,?)
    `
    const [res] = await connection.execute(statement, [roleName, roleDesc])
    return res
  }
  async getRoleById(id) {
    const statement = `
      SELECT * FROM role WHERE id = ?;
    `
    const [res] = await connection.execute(statement, [id])
    return res[0]
  }
  async updateRole(id, roleName, roleDesc) {
    const statement = `
      UPDATE role SET roleName = ? ,roleDesc = ? WHERE id = ?;
    `
    const [res] = await connection.execute(statement, [roleName, roleDesc, id])
    return res
  }
  async removeRoleById(id) {
    const statement = `
      DELETE FROM role WHERE id = ?;
    `
    const [res] = await connection.execute(statement, [id])
    return res
  }
  async giveRights(roleId, rids) {
    rids.forEach(async item => {
      const statement = `
        INSERT INTO role_right (roleId,rightId) VALUES (?,?);
      `
      await connection.execute(statement,[roleId, item])
    })
  }
  async getRoleList() {
    const statement = `
      SELECT r.id,r.roleName,r.roleDesc,JSON_ARRAYAGG(JSON_OBJECT('id',rs.id,'authName',rs.authName,'path',rs.path,'level',rs.level,'pid',rs.pid)) children FROM role r LEFT JOIN role_right rr on r.id = rr.roleId
      LEFT JOIN rights rs on rr.rightId = rs.id
      GROUP BY r.id
    `
    const [res] = await connection.execute(statement)
  
    return res
  }
  async getRoleListById(id) {
    const statement = `
      SELECT r.id,r.roleName,r.roleDesc,JSON_ARRAYAGG(JSON_OBJECT('id',rs.id,'authName',rs.authName,'path',rs.path,'level',rs.level,'pid',rs.pid)) children FROM role r LEFT JOIN role_right rr on r.id = rr.roleId
      LEFT JOIN rights rs on rr.rightId = rs.id
      GROUP BY r.id
      HAVING r.id = ?;
    `
    const [res] = await connection.execute(statement,[id])
  
    return res
  }
  async removeRight(roleId, rightId) {
    const statement = `
      DELETE FROM role_right WHERE roleId = ? AND rightId = ?;
    `
    const [res] = await connection.execute(statement,[roleId,rightId])
    return res
  }
}
module.exports = new RoleService()